package 数据结构.栈和队列.栈.顺序栈;

import  数据结构.栈和队列.栈.myStaticIne;

import java.util.Arrays;

public class ArrayStack<E> implements myStaticIne{
    private Object[] stack;
    private int top;
    private static final int DEFAULT_CAPACITY = 2;

    public ArrayStack() {
        top = -1;
        stack = new Object[DEFAULT_CAPACITY];
    }

    @Override
    public void push(Object item) {
        if(top == DEFAULT_CAPACITY - 1){
            ensureCapacity();
        }
        stack[++top] = item;
    }

    private void ensureCapacity() {
        Object[] newStack = Arrays.copyOf(stack,size()*3/2);
        stack = newStack;
    }

    @Override
    public Object pop() {
        if(isEmpty()){
            throw new IllegalStateException("栈为空");
        }
        E item = (E) stack[top];
        stack[top--] = null;
        return item;
    }

    @Override
    public Object peek() {
        if(isEmpty()){
            throw new IllegalStateException("栈为空");
        }
        E item = (E) stack[top];
        return item;
    }

    @Override
    public boolean isEmpty() {
        return top == -1;
    }

    @Override
    public int size() {
        return top + 1;
    }
}

